<template>
	<view class="zxbmain">
		<view class="tabBox">
			<view class="item" :class="{'selected':active==1}" @click="setTab(1)">个人咨询包（{{selfPackages.length}}个）</view>
			<view class="item" :class="{'selected':active==2}" @click="setTab(2)">公司咨询包（{{companyPackages.length}}个）</view>
		</view>
		<radio-group @change="radioChange">
			<view class="zxbInfo" v-for="dt in couponLists" :key="dt._id">
				<view class="xxbox">
					<view class="name">{{dt.productId.title}}</view>
					<template v-if="active==2 && dt.companyId">
						<view class="syqk">
							公司名称：{{dt.companyId.name}}
						</view>
						<view class="syqk" v-if="dt.teachers && dt.teachers.length>0">
							服务专家：
							<template v-for="dt2 in dt.teachers" :key="dt2._id">
								{{dt2.name}},
							</template>
						</view>
					</template>
					<view class="syqk" v-if="dt.productId.type==2">
						使用情况：已使用{{dt.usedNumber}}次
					</view>
					<view class="syqk" v-else-if="dt.productId.type==3">
						使用情况：已使用{{dt.usedNumber}}次，剩余{{dt.productId.quantity-dt.usedNumber}}次
					</view>
					<view class="express">有效期：{{dateFormat('Y-m-d',dt.startTime)}} ~ {{dateFormat('Y-m-d',dt.endTime)}}</view>
				</view>
				<view class="rdbox"><radio :value="dt._id"/></view>
			</view>
		</radio-group>
	</view>
</template>

<script>
	import {defineComponent,reactive,toRefs,onMounted,computed,getCurrentInstance} from 'vue'
	import { useStore } from 'vuex'
	import {getOrderList,packageUseCount,getCustomList} from "@/api/consult.js"
	import {toast,dateFormat} from '@/utils/common.js'
	export default defineComponent({
		props:{
			title:String,
			//lists:Array
		},
		setup(props,context) {
			const store = useStore()
			const {proxy} = getCurrentInstance()
			
			const state = reactive({
				imgUrlPrefix:getApp().globalData.imgUrlPrefix,
				userInfo:computed(()=>store.state.base.userInfo),
				zxbId:'',
				coupons:'',
				couponsTotal:0,
				countData:'',
				active:1,
				selfPackages:[],  // 个人咨询包列表
				companyPackages:[] ,// 企业咨询包列表
				couponLists:[]
			})
			
			onMounted(async ()=>{
				state.selfPackages = await get_coupon_list(1)
				if(state.userInfo.companyId && state.userInfo.companyId.length>0){
					state.companyPackages = await get_coupon_list(2)
				}
				
				proxy.$emit('reqOver',state.selfPackages.length+state.companyPackages.length)
				//console.log("state.selfPackages:",state.selfPackages)
				//console.log("state.companyPackages:",state.companyPackages)
				if(state.active==2){
					state.couponLists = state.companyPackages
				}else{
					state.couponLists = state.selfPackages
				}
			})
			
			const setTab = (index)=>{
				state.active = index
				state.pageIndex = 1
				proxy.$emit('change','')
				if(state.active==2){
					state.couponLists = state.companyPackages
				}else{
					state.couponLists = state.selfPackages
				}
				//get_coupon_list()
			}
			
			// 咨询包
			const get_coupon_list = (packageType)=>{
				return new Promise((resolve,reject) =>{
					let params = {
						status:1,
						pageIndex:1,
						pageSize:1000,
						orderType:63
					}
					if(packageType==2){ // 公司咨询包
						params.companyId = state.userInfo.companyId
					}else{ // 个人咨询包
						params.userId = state.userInfo._id
					}
					getOrderList(params).then(async res =>{
						if(res.code == 200){
							state.coupons = []
							// 过滤咨询包
							const res2 = await packageUseCount()
							if(res2.code == 200){
								state.countData = res2.data
								res.data.data.forEach(item =>{
									// 查找该咨询包使用的次数
									const fData = state.countData.find(item2 => item2._id == item._id)
									if(item.productId.type==3){ // 限次咨询包	
										if(fData){
											if(fData.count<item.productId.quantity){ // 未超过限制次数，可使用
												item.usedNumber = fData.count  // 添加字段：已使用次数
												state.coupons.push(item)
											}else{ // 已超次数。不能使用
												
											}
										}else{ // 说明还没有使用
										item.usedNumber = 0
											state.coupons.push(item)
										}
									}else if(item.productId.type==2){ // 限时咨询包
										// 判断当前时间是否在有效期内
										const nowTime = new Date().getTime() // 当前时间戳
										const startTime = new Date(item.startTime).getTime()
										const endTime = new Date(item.endTime).getTime()
										if(nowTime>startTime && nowTime<endTime){
											item.usedNumber = fData.count || 0  // 添加字段：已使用次数
											state.coupons.push(item)
										}
									}
								})
							}
							//state.coupons = res.data.data
							state.couponsTotal = state.coupons.length
							
							// 查找服务专家
							if(packageType==2){ // 公司咨询包
								for(let i=0;i<state.coupons.length;i++){
									const item = state.coupons[i]
									// 循环查找该公司的服务专家(后台分配的专家负责某个公司)
									const rt = await getCustomList({
										serviceId:item.productId.owner,  // 咨询包的所有者
										customId:item.companyId._id  // 购买咨询包的公司
									})
									if(rt.code == 200 && rt.data.data.length>0){
										item.teachers = rt.data.data[0].experter  // 添加字段
									}
								}
							}
							
							console.log("state.coupons:",state.coupons)
							
						}else{
							toast('获取数据出错了！')
						}
						//proxy.$emit('reqOver',state.couponsTotal)
						resolve(state.coupons)
					})
				})
			}
			
			const radioChange =(e)=> {
				console.log(e);
				if(state.zxbId!=e.detail.value){
					proxy.$emit('change',e.detail.value)
				}
				state.zxbId = e.detail.value
			}
			
			const get_use_count = (id) => {
			  if (state.countData) {
			    const fData = state.countData.find(item => item._id == id)
			    if (fData) {
			      return fData.count
			    } else {
			      return 0
			    }
			  }
			}
			// 检查下单对于的专家是否在公司服务专家数组里面
			const checkUseForTeacher=(couponId,teacherId)=>{
				if(state.active==1){  // 个人咨询包，不做判断
					return true
				}
				const couponItem = state.coupons.find(item => item._id == couponId)
				if(couponItem.teachers && couponItem.teachers.length>0){
					const teacher = couponItem.teachers.find(item => item._id == teacherId)
					if(teacher){
						return true
					}else{
						return false
					}
				}else{
					return false
				}
			}
			
			return {
				...toRefs(state),
				radioChange,
				dateFormat,
				get_use_count,
				setTab,
				checkUseForTeacher
			}
		}
		
		
	})
</script>

<style lang="scss" scoped>
	.zxbmain{
		flex: 1;
		flex-shrink: 0;
		padding: 20rpx;
		padding-top: 40rpx;
		.zxbInfo{
			display: flex;
			border-radius: 15rpx;
			box-shadow: 0 0 4px rgba(0, 0, 0, 0.1);
			background: #fff;
			padding: 20rpx;
			&+.zxbInfo{
				margin-top: 20rpx;
			}
			.xxbox{
				flex: 1;
				flex-shrink: 0;
				line-height: 50rpx;
				.name{
					font-size: 30rpx;
					font-weight: bold;
				}
				.express{
					font-size: 28rpx;
					color: #999;
					padding: 0;
				}
			}
			.rdbox{
				display: flex;
				align-items: center;
				padding: 0 0 0 15rpx;
			}
		}
	}
	.tabBox{
		display: flex;
		margin: -40rpx 0 20rpx 0;
		.item{
			display: flex;
			flex: 1;
			align-items: center;
			justify-content: center;
			height: 80rpx;
			font-size: 28rpx;
			&.selected{
				color: #e3af2f;
				position: relative;
				z-index: 10;
				&:before{
					content: '';
					position: absolute;
					z-index: 11;
					width: 100%;
					left: 0;
					bottom: 0;
					height: 2px;
					background: #e3af2f;
				}
			}
		}
	}
</style>